import { store } from '@/store'
import { defineStore } from 'pinia'
import { CACHE_KEY, useCache, deleteShopCache } from '@/hooks/web/useCache'
import { ShopInfoApi, ShopInfoVO } from '@/api/mall/shop/info'
import { ShopCategoryVO } from '@/api/mall/shop/category'

const { wsCache } = useCache()

interface ShopStoreInfo {
  isSetShopInfo: boolean
  shopInfo: ShopInfoVO
  categoryInfo: ShopCategoryVO
}
export const useShopStore = defineStore('shop', {
  state: (): ShopStoreInfo => ({
    isSetShopInfo: false,
    shopInfo: {} as ShopInfoVO,
    categoryInfo: {} as ShopCategoryVO
  }),
  getters: {
    getShopInfo(): ShopInfoVO {
      if (this.shopInfo) {
        return this.shopInfo
      }
      this.shopInfo = wsCache.get(CACHE_KEY.SHOP)
      return this.shopInfo || {}
    },
    getCategoryInfo(): ShopCategoryVO {
      if (this.categoryInfo) {
        return this.categoryInfo
      }
      this.categoryInfo = wsCache.get(CACHE_KEY.SHOP_CATEGORY)
      return this.categoryInfo || {}
    }
  },
  actions: {
    async setShopInfoAction() {
      this.shopInfo = wsCache.get(CACHE_KEY.SHOP)
      if (!this.shopInfo) {
        try {
          this.shopInfo = await ShopInfoApi.getMyShopInfo()
          wsCache.set(CACHE_KEY.SHOP, this.shopInfo)
        } catch (error) {
          this.shopInfo = {} as ShopInfoVO
        }
      }
      this.isSetShopInfo = true
    },
    async setCategoryInfoAction() {
      this.categoryInfo = wsCache.get(CACHE_KEY.SHOP_CATEGORY)
      if (!this.categoryInfo) {
        try {
          this.categoryInfo = await ShopInfoApi.getMyCategoryInfo()
          wsCache.set(CACHE_KEY.SHOP_CATEGORY, this.categoryInfo)
        } catch (error) {
          this.categoryInfo = {} as ShopCategoryVO
        }
      }
    },
    loginOut() {
      deleteShopCache()
      this.isSetShopInfo = false
      this.shopInfo = {} as ShopInfoVO
      this.categoryInfo = {} as ShopCategoryVO
    }
  }
})

export const useShopStoreWithOut = () => {
  return useShopStore(store)
}
